package com.atguigu.gmall.ums.service.impl;

import com.atguigu.gmall.common.exception.GmallException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.ums.mapper.UserMapper;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.ums.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<UserEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<UserEntity>()
        );

        return new PageResultVo(page);
    }


    /**
     * 检查用户参数是否被占用的接口
     * 检查username、phone、email三个参数不重复就可以了
     * check/18232323232/2  --2表示检查自的类型是phone，上一级路径表示检查的手机号码值
     * 1- username
     * 2- phone
     * 3- email
     */
    @Override
    public Boolean check(String data, Integer type) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        switch (type) {
            case 1:
                wrapper.eq(UserEntity::getUsername, data);
                break;
            case 2:
                wrapper.eq(UserEntity::getPhone, data);
                break;
            case 3:
                wrapper.eq(UserEntity::getEmail, data);
                break;
            default:
                return null;
        }
        Long count = baseMapper.selectCount(wrapper);
        return count <= 0;
    }

    /**
     * 注册接口：
     */
    @Override
    public Boolean register(UserEntity userEntity, String code) {
        //1.检查参数是否正确(为了防止空指针)
        //2.判断验证码是否正确[从redis中获取当前userEntity.phone对应的code，判断是否与前端传来的一致] 略
        //3.对userEntity的密码进行加密
        //4.需要将数据库需要的但前端没有提交的数据 初始化设置
        //5.删除redis中的验证码（不删也可以） 略
        if (StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(userEntity.getUsername()) ||
                StringUtils.isEmpty(userEntity.getPassword()) ||
                StringUtils.isEmpty(userEntity.getPhone()) ||
                StringUtils.isEmpty(userEntity.getEmail())
        ) {
            return false;
        }
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 8);//为每个用户，(使用UUID)生成8位数的随机盐
        userEntity.setSalt(salt);//将随机盐存入用户，方便下次登录时核对密码
        userEntity.setPassword(DigestUtils.md5Hex(salt + userEntity.getPassword()));//使用apache提供的工具类对密码惊醒MD5加盐加密
        userEntity.setNickname(userEntity.getUsername());//昵称自动使用用户名
        userEntity.setIntegration(10000);
        userEntity.setGrowth(10000);
        userEntity.setLevelId(1L);//
        userEntity.setStatus(1);//1表示白名单，0表示黑名单
        userEntity.setCreateTime(new Date());

        return this.save(userEntity);//这里不用baseMapper.insert，因为insert方法返回值是int，而save返回值是boolean

    }


    /**
     * 使用账号和密码查询账户接口：
     */
    @Override
    public UserEntity checkAccount(String account, String password) {
        //1.查询账户，
        //2.多重账户校验
        //3.对密码进行加密计算，与数据库中的对比

        //select * from ums_user where (username=account or phone=account or email=account)
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getUsername, account).or().eq(UserEntity::getPhone, account).eq(UserEntity::getEmail, account);
        List<UserEntity> userEntities = baseMapper.selectList(wrapper);
        if (userEntities.size() <= 0) {
            return null;
        } else if (userEntities.size() > 1) {
            throw new GmallException("查询到同名账户");
        } else {
            UserEntity userEntity = userEntities.get(0);
            String secretPassword = DigestUtils.md5Hex(userEntity.getSalt() + password);
            if (secretPassword == userEntity.getPassword()) {
                return userEntity;
            }
            return null;
        }
    }


    public void queryByUsername(String username, String phone, String email) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username).or().eq("phone", phone).or();
        wrapper.eq("email", email);
        Long count = baseMapper.selectCount(wrapper);
        if (count <= 0) {
            return;
        }
    }


}